package com.wan.config;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

	// 构造函数
	public AgeRoutePredicateFactory() {
		super(Config.class);
	}

	// 定义参数顺序
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge", "maxAge");
	}

	// 定义比较规则
	@Override
	public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
		return exchange -> {
			// 获取查询参数中的 age 值
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			return isAgeValid(ageStr, config);
		};
	}

	// 校验 age 是否符合规则
	private boolean isAgeValid(String ageStr, AgeRoutePredicateFactory.Config config) {
		if (!StringUtils.isEmpty(ageStr)) {
			try {
				int age = Integer.parseInt(ageStr);
				return age >= config.getMinAge() && age <= config.getMaxAge();
			} catch (NumberFormatException e) {
				// 如果 age 不是有效的整数，可以选择记录日志或者返回 false
				return false;
			}
		}
		return false;
	}

	// 配置类
	@Data
	static class Config {
		private int minAge;
		private int maxAge;
	}
}